<template>
  <span :style="day === 0 ? 'color:#FF9F0F' : ''" class="time">
    <i class="iconfont icon-shijian"></i>
    <span style="font-size: 14px; margin-left: 10px">
      <span>仅剩{{ day }}天{{ hours }}小时{{ min }}分钟</span>
    </span>
  </span>
</template>

<script>
// 倒计时组件
export default {
  props: {
    endDate: {
      type: String
    }
  },
  data() {
    return {
      day: 0,
      hours: 0,
      min: 0,
      second: 0,
      endTime: this.endDate,
      timer: null
    }
  },
  mounted() {
    this.countTime()
  },
  methods: {
    countTime() {
      // 清除定时器
      clearInterval(this.timer)
      // 获取当前时间
      let date = new Date()
      let now = date.getTime()
      // 兼容safari浏览器
      let endtime = this.endTime.replace(/-/g, '/')
      // 设置截止时间
      let endDate = new Date(endtime) // this.endTime需要倒计时的日期
      let end = endDate.getTime()
      // 时间差
      let leftTime = end - now
      // 定义变量 d,h,m,s保存倒计时的时间
      if (leftTime >= 0) {
        // 天
        this.day = Math.floor(leftTime / 1000 / 60 / 60 / 24)
        // 时
        let h = Math.floor((leftTime / 1000 / 60 / 60) % 24)
        this.hours = h < 10 ? '0' + h : h
        // 分
        let m = Math.floor((leftTime / 1000 / 60) % 60)
        this.min = m < 10 ? '0' + m : m
        // 秒
        let s = Math.floor((leftTime / 1000) % 60)
        this.second = s < 10 ? '0' + s : s
      } else {
        this.day = 0
        this.hour = '00'
        this.min = '00'
        this.second = '00'
      }
      // 等于0的时候不调用
      if (Number(this.hours) === 0 && Number(this.day) === 0 && Number(this.min) === 0 && Number(this.second) === 0) {
        this.$emit('getBidingList')
        clearInterval(this.timer)
      }
      if (Number(this.hours) === 0 && Number(this.day) === 0 && Number(this.min) <= 5 && Number(this.second) != 0) {
        // 每秒执行一次
        this.timer = setInterval(this.countTime, 1000)
        // return;
      } else {
        // 每分钟调用countTime方法，显示动态时间效果,
        this.timer = setInterval(this.countTime, 60000)
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  watch: {
    endDate() {
      return (this.endTime = this.endDate)
    }
  }
}
</script>
<style lang="less" scoped>
.icon-shijian,
.icon-weizhi {
  font-size: 20px;
}
.time {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
